import datetime
import json
import logging
import webapp2

from google.appengine.ext import db


class Command(db.Model):
    ts = db.DateTimeProperty()
    cmd = db.StringProperty()
    ppid = db.IntegerProperty()
    pwd = db.StringProperty()
    username = db.StringProperty()
    hostname = db.StringProperty()

    def to_json(self):
        return {
            'ts': str(self.ts),
            'cmd': self.cmd,
            'ppid': self.ppid,
            'pwd': self.pwd,
            'username': self.username,
            'hostname': self.hostname,
            }


def default_encode(obj):
    if isinstance(obj, Command):
        return obj.to_json()
    raise TypeError(obj)


class Query(webapp2.RequestHandler):

    def get(self):
        cmds = list(Command.all().order('-ts').run())
        self.response.content_type = 'application/json'
        self.response.write(json.dumps(cmds, default=default_encode))


class Listen(webapp2.RequestHandler):

    def post(self):
        jsc = json.loads(self.request.body)
        logging.info(jsc)
        ts = datetime.datetime.strptime(jsc['ts'], '%Y-%m-%dT%H:%M:%S.%fZ')
        cmd = Command(
            ts=ts, cmd=jsc['cmd'], ppid=jsc['ppid'], pwd=jsc['pwd'],
            username=jsc['username'], hostname=jsc['hostname'])
        cmd.put()
        self.response.status = 204


app = webapp2.WSGIApplication(
    [('/api/listen', Listen),
     ('/api/query', Query)],
    debug=True)
